/*
 * @Author: 马思宁 598138645@qq.com
 * @Date: 2024-04-08 09:54:25
 * @LastEditors: 马思宁 598138645@qq.com
 * @LastEditTime: 2024-05-15 17:50:34
 * @FilePath: \v-koa\src\utils\handle-error.js
 * @Description: 错误处理
 */
const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  NAME_IS_ALREADY_EXISTS,
  NAME_IS_NOT_EXISTS,
  PASSWORD_IS_INCORRENT,
  UNAUTHORIZATION,
  OPERATION_IS_NOT_ALLOWED,
  RESOURCE_IS_NOT_EXISTS,
} = require("../config/error");

function handleError(error, ctx) {
  let code = 0;
  let msg = "";
  switch (error) {
    case NAME_OR_PASSWORD_IS_REQUIRED:
      code = 400;
      msg = "用户名或者密码不能为空";
      break;
    case NAME_IS_ALREADY_EXISTS:
      code = 409;
      msg = "用户名已经被占用，请输入新的用户名";
      break;
    case NAME_IS_NOT_EXISTS:
      code = 500;
      msg = "用户名不存在，请检查用户名";
      break;
    case PASSWORD_IS_INCORRENT:
      code = 500;
      msg = "输入的密码错误，请检查密码";
      break;
    case UNAUTHORIZATION:
      code = 401;
      msg = "无效的token或者token已经过期";
      break;
    case OPERATION_IS_NOT_ALLOWED:
      code = 403;
      msg = "没有操作该资源的权限";
      break;
    case RESOURCE_IS_NOT_EXISTS:
      code = 404;
      msg = "在资源在数据库中不存在，请检查资源";
      break;
  }
  ctx.body = {
    code,
    msg,
  };
}
module.exports = handleError;
